<?php
/**
 * 交易管理
 *
 *
 *
*/

defined('IN_NWIDC') or exit('Access Invalid!');
class orderControl extends SystemControl{
    /**
     * 每次导出订单数量
     * @var int
     */
	const EXPORT_SIZE = 1000;

	public function __construct(){
		parent::__construct();
		Language::read('trade');
	}

	public function indexOp(){
	    $model_order = Model('order');
        $condition	= array();
        if($_GET['order_sn']) {
        	$condition['order_sn'] = $_GET['order_sn'];
        }
        if($_GET['store_name']) {
            $condition['store_name'] = $_GET['store_name'];
        }
        if(in_array($_GET['order_state'],array('0','10','20','30','40'))){
        	$condition['order_state'] = $_GET['order_state'];
        }
        if($_GET['payment_code']) {
            $condition['payment_code'] = $_GET['payment_code'];
        }
        if($_GET['buyer_name']) {
            $condition['buyer_name'] = $_GET['buyer_name'];
        }
        if($_GET['tax_order'] == 1){
        	$condition['is_tax_order'] = 1;
        }
		if($_GET['order_type']){
			if('is_whole' == $_GET['order_type']){
				$condition['is_whole'] = 1;
			}
			if('is_we_groupbuy' == $_GET['order_type']){
				$condition['is_we_groupbuy'] = array("neq", 0);
			}
		}
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/',$_GET['query_start_time']);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/',$_GET['query_end_time']);
        $start_unixtime = $if_start_time ? strtotime($_GET['query_start_time']) : null;
        $end_unixtime = $if_end_time ? strtotime($_GET['query_end_time']): null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('time',array($start_unixtime,$end_unixtime));
        }
        $order_list	= $model_order->getOrderList($condition,30);

        foreach ($order_list as $order_id => $order_info) {
            //显示取消订单
            $order_list[$order_id]['if_cancel'] = $model_order->getOrderOperateState('system_cancel',$order_info);
            //显示收到货款
            $order_list[$order_id]['if_system_receive_pay'] = $model_order->getOrderOperateState('system_receive_pay',$order_info);
        }
        //显示支付接口列表(搜索)
        $payment_list = Model('payment')->getPaymentOpenList();
        Tpl::output('payment_list',$payment_list);

        Tpl::output('order_list',$order_list);
        Tpl::output('show_page',$model_order->showpage());
        Tpl::showpage('order.index');
	}

	/**
	 * 平台订单状态操作
	 *
	 */
	public function change_stateOp() {
        $order_id = intval($_GET['order_id']);
        if($order_id <= 0){
            showMessage(L('miss_order_number'),$_POST['ref_url'],'html','error');
        }
        $model_order = Model('order');

        //获取订单详细
        $condition = array();
        $condition['order_id'] = $order_id;
        $order_info	= $model_order->getOrderInfo($condition);

        if ($_GET['state_type'] == 'cancel') {
            $result = $this->_order_cancel($order_info);
        } elseif ($_GET['state_type'] == 'receive_pay') {
            $result = $this->_order_receive_pay($order_info,$_POST);
        }
        if (!$result['state']) {
            showMessage($result['msg'],$_POST['ref_url'],'html','error');
        } else {
            showMessage($result['msg'],$_POST['ref_url']);
        }
	}

	/**
	 * 系统取消订单
	 */
	private function _order_cancel($order_info) {
	    $order_id = $order_info['order_id'];
	    $model_order = Model('order');
	    $logic_order = Logic('order');
	    $if_allow = $model_order->getOrderOperateState('system_cancel',$order_info);
	    if (!$if_allow) {
	        return callback(false,'无权操作');
	    }
	    $result =  $logic_order->changeOrderStateCancel($order_info,'system', $this->admin_info['name']);
        if ($result['state']) {
            $this->log(L('order_log_cancel').','.L('order_number').':'.$order_info['order_sn'],1);
        }
        return $result;
	}

	/**
	 * 系统收到货款
	 * @throws Exception
	 */
	private function _order_receive_pay($order_info, $post) {
	    $order_id = $order_info['order_id'];
	    $model_order = Model('order');
	    $logic_order = Logic('order');
//	    $if_allow = $model_order->getOrderOperateState('system_receive_pay',$order_info);
//	    if (!$if_allow) {
//	        return callback(false,'无权操作');
//	    }

	    if (!chksubmit()) {
	        Tpl::output('order_info',$order_info);
	        //显示支付接口列表
	        $payment_list = Model('payment')->getPaymentOpenList();
	        //去掉预存款和货到付款
	        foreach ($payment_list as $key => $value){
	            if ($value['payment_code'] == 'predeposit' || $value['payment_code'] == 'offline') {
	               unset($payment_list[$key]);
	            }
	        }
	        Tpl::output('payment_list',$payment_list);
	        Tpl::showpage('order.receive_pay');
	        exit();
	    }
	    $order_list	= $model_order->getOrderList(array('pay_sn'=>$order_info['pay_sn'],'order_state'=>ORDER_STATE_NEW));
	    $result = $logic_order->changeOrderReceivePay($order_list,'system',$this->admin_info['name'],$post);
        if ($result['state']) {
            $this->log('将订单改为已收款状态,'.L('order_number').':'.$order_info['order_sn'],1);
        }
	    return $result;
	}

	/**
	 * 查看订单
	 *
	 */
	public function show_orderOp(){
	    $order_id = intval($_GET['order_id']);
	    if($order_id <= 0 ){
	        showMessage(L('miss_order_number'));
	    }
        $model_order	= Model('order');
        $order_info	= $model_order->getOrderInfo(array('order_id'=>$order_id),array('order_goods','order_common','store'));

        //订单变更日志
		$log_list	= $model_order->getOrderLogList(array('order_id'=>$order_info['order_id']));
		Tpl::output('order_log',$log_list);

		//退款退货信息
        $model_refund = Model('refund_return');
        $condition = array();
        $condition['order_id'] = $order_info['order_id'];
        $condition['seller_state'] = 2;
        $condition['admin_time'] = array('gt',0);
        $return_list = $model_refund->getReturnList($condition);
        Tpl::output('return_list',$return_list);

        //退款信息
        $refund_list = $model_refund->getRefundList($condition);
        Tpl::output('refund_list',$refund_list);

		//卖家发货信息
		if (!empty($order_info['extend_order_common']['daddress_id'])) {
		    $daddress_info = Model('daddress')->getAddressInfo(array('address_id'=>$order_info['extend_order_common']['daddress_id']));
		    Tpl::output('daddress_info',$daddress_info);
		}
        if (empty($order_info['extend_order_common']['reciver_info']['phone'])) {
            $order_info['extend_order_common']['reciver_info']['phone'] = $order_info['extend_order_common']['reciver_info']['mob_phone'];
        }
        if(!empty($order_info['extend_order_common']['reciver_info']['area_info'] ) && strpos($order_info['extend_order_common']['reciver_info']['address'], $order_info['extend_order_common']['reciver_info']['area_info']) === false){
            $order_info['extend_order_common']['reciver_info']['address'] = $order_info['extend_order_common']['reciver_info']['area_info'] . ' '  . $order_info['extend_order_common']['reciver_info']['address'] ;
        }

		Tpl::output('order_info',$order_info);
        Tpl::showpage('order.view');
	}

	/**
	 * 编辑订单
	 *
	 */
	public function edit_orderOp(){
		if($_GET['order_id']) {
			$this->get_edit_order();
		}
		if($_POST['order_id']) {
			$this->update_edit_order();
		}

	}

	private function get_edit_order(){
		$order_id = intval($_GET['order_id']);
		if($order_id <= 0 ){
			showMessage(L('miss_order_number'));
		}
		$model_order	= Model('order');
		$order_info	= $model_order->getOrderInfo(array('order_id'=>$order_id),array('order_goods','order_common','store'));

		//订单变更日志
		$log_list	= $model_order->getOrderLogList(array('order_id'=>$order_info['order_id']));
		Tpl::output('order_log',$log_list);

		//退款退货信息
		$model_refund = Model('refund_return');
		$condition = array();
		$condition['order_id'] = $order_info['order_id'];
		$condition['seller_state'] = 2;
		$condition['admin_time'] = array('gt',0);
		$return_list = $model_refund->getReturnList($condition);
		Tpl::output('return_list',$return_list);

		//退款信息
		$refund_list = $model_refund->getRefundList($condition);
		Tpl::output('refund_list',$refund_list);

//		var_dump($order_info['extend_order_common']);
		//卖家发货信息
		if (!empty($order_info['extend_order_common']['daddress_id'])) {
			$daddress_info = Model('daddress')->getAddressInfo(array('address_id'=>$order_info['extend_order_common']['daddress_id']));
			Tpl::output('daddress_info',$daddress_info);
		}
		Tpl::output('order_info',$order_info);
		Tpl::showpage('order.edit');
	}

	private function update_edit_order() {
		$data = $_POST;
		header("Content-type:text/html;charset=utf-8");
		var_dump($data);
		// exit;
		$order_id = $_POST['order_id'];
		$order_state = $_POST['order_state'];
		$order_goods = $_POST['goods'];
		$model_order = Model('order');
		//
		$condition = array();
		$condition['order_id'] = $order_id;
		$order_info	= $model_order->getOrderInfo(array('order_id'=>$order_id),array('order_goods','order_common','store'));
		if(empty($order_info)) {
			throw new Exception('不存在该订单信息');
		}
		//
		$reciver_info = $order_info['extend_order_common']['reciver_info'];
		$reciver_info['true_name']    = $_POST['reciver_name'];
		$reciver_info['address']      = $_POST['address'];
		$reciver_info['mob_phone']    = $_POST['mob_phone'];
		$update_order_common = array();
		$update_order_common['reciver_info'] = serialize($reciver_info);
		$update_order_common['reciver_name'] = $reciver_info['true_name'];
		$update = $model_order->editOrderCommon($update_order_common,array('order_id'=>$order_id));
		if (!$update) {
			throw new Exception('更新失败');
		}
		//
		$order_amount = 0;
		foreach($order_goods as $k => $goods){
			$g_info = $model_order->getOrderGoodsInfo(['order_id'=>$order_id, 'goods_id'=> $k]);
			$goods_tax = $goods['goods_price'] * (intval($g_info['tax']/$g_info['goods_price']*100))/100;
			$goods_pay_price = $goods['goods_price'] + $goods_tax;
			$order_amount += $goods['goods_num'] *  $goods_pay_price;
			$model_order->editOrderGoods(['goods_price'=>$goods['goods_price'], 'goods_num'=>$goods['goods_num'], 'goods_pay_price'=>$goods_pay_price, 'tax'=>$goods_tax], ['order_id'=>$order_id, 'goods_id'=> $k]);
		}
		//
		$update_order = array();
		$update_order['order_amount'] = $order_amount + $order_info['shipping_fee'];
		$update = $model_order->editOrder($update_order,array('order_id'=>$order_id));

		if (!$update) {
			throw new Exception('更新失败');
		}
		if($order_state <= $order_info['order_state']) {
			if($order_state == ORDER_STATE_CANCEL) {
				$this->edit_order_to_success($data, $order_info);
				$this->edit_order_to_send($data, $order_info);
				$this->edit_order_to_pay($data, $order_info);
				$this->edit_order_to_new($data, $order_info);
				$this->edit_order_to_cancel($data, $order_info);
			}
			if($order_state == ORDER_STATE_NEW) {
				$this->edit_order_to_success($data, $order_info);
				$this->edit_order_to_send($data, $order_info);
				$this->edit_order_to_pay($data, $order_info);
				$this->edit_order_to_new($data, $order_info);
			}
			if($order_state == ORDER_STATE_PAY) {
				$this->edit_order_to_success($data, $order_info);
				$this->edit_order_to_send($data, $order_info);
				$this->edit_order_to_pay($data, $order_info);
			}
			if($order_state == ORDER_STATE_SEND) {
				$this->edit_order_to_success($data, $order_info);
				$this->edit_order_to_send($data, $order_info);
			}
			if($order_state == ORDER_STATE_SUCCESS) {
				$this->edit_order_to_success($data, $order_info);
			}
		}
		showMessage('更改成功','index.php?act=order&op=edit_order&order_id='.$order_id,'html','succ');
	}

	/*
	 * 强制更新订单状态为【取消】
	 * */
	private function edit_order_to_cancel($post_data, $order_info) {
		$order_id = $post_data['order_id'];
		$model_order = Model('order');
		$update_order = array();
		$update_order['order_state'] = ORDER_STATE_CANCEL;
		$update_order['finnshed_time'] = 0;
		$update1 = $model_order->editOrder($update_order,array('order_id'=>$order_id));
		if (!$update1) {
			throw new Exception('order更新失败');
		}
		$update_order_common = array();
		$update_order_common['daddress_id'] = 0;
		$update2 = $model_order->editOrderCommon($update_order_common,array('order_id'=>$order_id));
		if (!$update2) {
			throw new Exception('order_common更新失败');
		}
		// 删除订单log
		$contion_order_log = array("order_id"=>$order_id, "log_orderstate"=>['gt', ORDER_STATE_CANCEL]);
		Model()->table('order_log')->where($contion_order_log)->delete();
	}

	/*
	 * 强制更新订单状态为【新订单】
	 * */
	private function edit_order_to_new($post_data, $order_info) {
		$order_id = $post_data['order_id'];
		$model_order = Model('order');
		$update_order = array();
		$update_order['order_state'] = ORDER_STATE_NEW;
		$update_order['finnshed_time'] = 0;
		$update_order['payment_code'] = '';
		$update_order['payment_time'] = 0;
		$update_order['shipping_code'] = '';
		$update_order['refund_state'] = 0;
		$update_order['refund_amount'] = 0;
		$update = $model_order->editOrder($update_order,array('order_id'=>$order_id));
		if (!$update) {
			throw new Exception('更新失败');
		}

		$update_order_common = array();
		$update_order_common['daddress_id'] = 0;
		$update2 = $model_order->editOrderCommon($update_order_common,array('order_id'=>$order_id));
		if (!$update2) {
			throw new Exception('order_common更新失败');
		}

		// 删除订单log
		$contion_order_log = array("order_id"=>$order_id, "log_orderstate"=>array(['gt', ORDER_STATE_NEW], ['eq', ORDER_STATE_CANCEL], 'or'));
		Model()->table('order_log')->where($contion_order_log)->delete();
	}

	/*
	 * 强制更新订单状态为【已支付】
	 * */
	private function edit_order_to_pay($post_data, $order_info) {
		$order_id = $post_data['order_id'];
		$model_order = Model('order');
		$update_order = array();
		$update_order['order_state'] = ORDER_STATE_PAY;
		$update_order['finnshed_time'] = 0;
		$update_order['shipping_code'] = '';
		$update_order['refund_state'] = 0;
		$update_order['refund_amount'] = 0;
		$update = $model_order->editOrder($update_order,array('order_id'=>$order_id));
		if (!$update) {
			throw new Exception('更新失败');
		}

		$update_order_common = array();
		$update_order_common['shipping_time'] = 0;
		$update_order_common['shipping_express_id'] = 0;
		$update_order_common['daddress_id'] = 0;
		$update2 = $model_order->editOrderCommon($update_order_common,array('order_id'=>$order_id));
		if (!$update2) {
			throw new Exception('order_common更新失败');
		}
		// 删除订单log
		$contion_order_log = array("order_id"=>$order_id, "log_orderstate"=>array(['gt', ORDER_STATE_PAY], ['eq', ORDER_STATE_CANCEL], 'or'));
		Model()->table('order_log')->where($contion_order_log)->delete();
	}

	/*
	 * 强制更新订单状态为【已发货】
	 * */
	private function edit_order_to_send($post_data, $order_info) {
		$order_id = $post_data['order_id'];
		$model_order = Model('order');
		$update_order = array();
		$update_order['order_state'] = ORDER_STATE_SEND;
		$update_order['finnshed_time'] = 0;
		$update = $model_order->editOrder($update_order,array('order_id'=>$order_id));
		if (!$update) {
			throw new Exception('更新失败');
		}
		// 降订单状态
		if($order_info['order_state'] == ORDER_STATE_SUCCESS) {
			// 删除订单log
			$contion_order_log = array("order_id"=>$order_id, "log_orderstate"=>array(['gt', ORDER_STATE_SEND], ['eq', ORDER_STATE_CANCEL], 'or'));
			Model()->table('order_log')->where($contion_order_log)->delete();
			// 刪除积分日志
			$contion_points_log = array("pl_desc"=>['like', '%'. $order_info['order_sn']. '%']);
			Model()->table('points_log')->where($contion_points_log)->delete();
			// 减去赠送积分
			$pl_points = 0;
			if ($order_info['order_amount']){
				$pl_points = @intval($order_info['order_amount']/C('points_orderrate'));
				if ($pl_points > intval(C('points_ordermax'))){
					$pl_points = intval(C('points_ordermax'));
				}
			}
			$data = array();
			$data['order_pointscount'] = array('exp','order_pointscount-'.$pl_points);
			$model_order->editOrderCommon($data,array('order_id'=>$order_id));
			// 更新member内容
			$obj_member = Model('member');
			$upmember_array = array();
			$upmember_array['member_points'] = array('exp','member_points-'.$pl_points);
			$obj_member->editMember(array('member_id'=>$order_info['buyer_id']),$upmember_array);
			// 删除经验日志
			$contion_exppoints_log = array("exp_desc"=>['like', '%'. $order_info['order_sn']. '%'], 'exp_stage'=>'order');
			Model()->table('points_log')->where($contion_exppoints_log)->delete();
		}
	}

	/*
	 * 强制更新订单状态为【已确认收货】
	 * */
	private function edit_order_to_success($post_data, $order_info) {
		Model()->table('order_log')->where(['order_id'=>$order_info['order_id']])->update(['log_time'=> strtotime($post_data['finnshed_time'])]);
	}

	/**
	 * 导出
	 *
	 */
	public function export_step1Op(){
		$lang	= Language::getLangContent();

	    $model_order = Model('order');
        $condition	= array();
        if($_GET['order_sn']) {
        	$condition['order_sn'] = $_GET['order_sn'];
        }
        if($_GET['store_name']) {
            $condition['store_name'] = $_GET['store_name'];
        }
        if(in_array($_GET['order_state'],array('0','10','20','30','40'))){
        	$condition['order_state'] = $_GET['order_state'];
        }
        if($_GET['payment_code']) {
            $condition['payment_code'] = $_GET['payment_code'];
        }
        if($_GET['buyer_name']) {
            $condition['buyer_name'] = $_GET['buyer_name'];
        }
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/',$_GET['query_start_time']);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/',$_GET['query_end_time']);
        $start_unixtime = $if_start_time ? strtotime($_GET['query_start_time']) : null;
        $end_unixtime = $if_end_time ? strtotime($_GET['query_end_time']): null;
        if ($start_unixtime || $end_unixtime) {
            $condition['add_time'] = array('time',array($start_unixtime,$end_unixtime));
        }

		if (!is_numeric($_GET['curpage'])){
			$count = $model_order->getOrderCount($condition);
			$array = array();
			if ($count > self::EXPORT_SIZE ){	//显示下载链接
				$page = ceil($count/self::EXPORT_SIZE);
				for ($i=1;$i<=$page;$i++){
					$limit1 = ($i-1)*self::EXPORT_SIZE + 1;
					$limit2 = $i*self::EXPORT_SIZE > $count ? $count : $i*self::EXPORT_SIZE;
					$array[$i] = $limit1.' ~ '.$limit2 ;
				}
				Tpl::output('list',$array);
				Tpl::output('murl','index.php?act=order&op=index');
				Tpl::showpage('export.excel');
			}else{	//如果数量小，直接下载
				$data = $model_order->getOrderList($condition,'','*','order_id desc',self::EXPORT_SIZE);
				$this->createExcel($data);
			}
		}else{	//下载
			$limit1 = ($_GET['curpage']-1) * self::EXPORT_SIZE;
			$limit2 = self::EXPORT_SIZE;
			$data = $model_order->getOrderList($condition,'','*','order_id desc',"{$limit1},{$limit2}");
			$this->createExcel($data);
		}
	}

	/**
	 * 生成excel
	 *
	 * @param array $data
	 */
	private function createExcel($data = array()){
		Language::read('export');
		import('libraries.excel');
		$excel_obj = new Excel();
		$excel_data = array();
		//设置样式
		$excel_obj->setStyle(array('id'=>'s_title','Font'=>array('FontName'=>'宋体','Size'=>'12','Bold'=>'1')));
		//header
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_no'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_store'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_buyer'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_xtimd'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_count'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_yfei'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_paytype'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_state'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_storeid'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_buyerid'));
		$excel_data[0][] = array('styleid'=>'s_title','data'=>L('exp_od_bemail'));
		//data
		foreach ((array)$data as $k=>$v){
			$tmp = array();
			$tmp[] = array('data'=>'NC'.$v['order_sn']);
			$tmp[] = array('data'=>$v['store_name']);
			$tmp[] = array('data'=>$v['buyer_name']);
			$tmp[] = array('data'=>date('Y-m-d H:i:s',$v['add_time']));
			$tmp[] = array('format'=>'Number','data'=>ncPriceFormat($v['order_amount']));
			$tmp[] = array('format'=>'Number','data'=>ncPriceFormat($v['shipping_fee']));
			$tmp[] = array('data'=>orderPaymentName($v['payment_code']));
			$tmp[] = array('data'=>orderState($v));
			$tmp[] = array('data'=>$v['store_id']);
			$tmp[] = array('data'=>$v['buyer_id']);
			$tmp[] = array('data'=>$v['buyer_email']);
			$excel_data[] = $tmp;
		}
		$excel_data = $excel_obj->charset($excel_data,CHARSET);
		$excel_obj->addArray($excel_data);
		$excel_obj->addWorksheet($excel_obj->charset(L('exp_od_order'),CHARSET));
		$excel_obj->generateXML($excel_obj->charset(L('exp_od_order'),CHARSET).$_GET['curpage'].'-'.date('Y-m-d-H',time()));
	}

	function record_orderOp(){
		$ids = $_POST['ids'];
        $base = dirname(BASE_PATH);
        $config = Model('setting')->getListSetting();
        require_once($base . '/custom/' . $config['custom_interface'] . '/controller.php');
        $class = $config['custom_interface'] . 'Controller';
        $ins = new $class;
        $ins->display('order',$ids);
        exit;
	}
}
